<template>
  <div class="product_list" :style="{ 'height': productsHeight }">

    <div class="page_img"></div>
    <div class="header">
      <van-nav-bar title="商品列表" class="nav_bar" :right-text="rightText()" @click-right="onClickRight" />
    </div>
    <!-- 供应商，商品名称搜索框 -->
    <div style="" class="product_list_serch_text">
      <van-search class="product_list_serch1" v-model="searchValue" background="#fff" @focus="showTop = true"
        placeholder="请输入商品名称/供应商名称/品牌名称">
        <template #left-icon>
          <div class="search_l_bt"></div>
        </template>
        <!-- <template #right-icon>
          <div class="search_r_bt">搜索</div>
        </template> -->
      </van-search>
      <div class="product_list_serch2">
        <div class="product_list-btn-screen" @click="handleListFlag">
          <div class="product_list-btn-screen-image"></div>
        </div>
      </div>
    </div>
    <!-- 筛选 -->
    <div class="mongolian_layers" v-show="showPop">
      <div class="mongolian_layers_options">
        <div class="mongolian_layers_options_scoll">
          <div class="title">商品状态</div>
          <div class="shelf_type anthor_type anthor_types">
            <div v-for="(item, index) in statusList" :key="index" class="anthor_type_div">
              <div @click="statusClicks(index)" :class="statusIndex !== index ? 'shelf_div' : 'shelf_div_avtive'">
                {{ item.name }}
              </div>
            </div>
          </div>
          <div class="title">选品主播</div>
          <div class="shelf_type anthor_type anthor_types">
            <div v-for="(item, index) in anchorList" :key="index" class="anthor_type_div">
              <div @click="anchorClicks(index)" :class="anchorIndex !== index ? 'shelf_div' : 'shelf_div_avtive'">
                {{ item.deptName }}
              </div>
            </div>
          </div>
        </div>
        <div class="buttons">
          <div class="reset" @click="reset">重置</div>
          <div class="submit" @click="submit">完成</div>
        </div>
      </div>
      <div class="mongolian_layers_layer" @click="showPop = false"></div>
    </div>
    <!-- 供应商，商品名称搜索弹窗 -->
    <div class="mongolian_layer" v-show="showTop">
      <div class="mongolian_layer_options">
        <div class="mongolian_layer_div" @click="onSearchs">按供应商搜索</div>
        <div class="mongolian_layer_div" @click="onSearch">按商品名称搜索</div>
        <div class="mongolian_layer_div" @click="onSearchBrand">按品牌名称搜索</div>
      </div>
      <div class="mongolian_layer_layer" @click="showTop = false"></div>
    </div>
    <!-- 类目。商品状态检索 -->
    <div class="screen">
      <div class="screen_div" @click="screenClicks()">
        <div class="screen_child">{{ catName }}</div>
        <van-image :src="heisexiasanjiao" class="screen_icons" />
      </div>
      <div class="screen_div" @click="statusClick()">
        <div class="screen_child">{{ ststusName }}</div>
        <van-image :src="heisexiasanjiao" class="screen_icons" />
      </div>
      <div class="screen_div" @click="investmentClick()" v-if="(userName.indexOf('recruitStaff') == -1)">
        <div class="screen_child">{{ investmentName }}</div>
        <van-image :src="heisexiasanjiao" class="screen_icons" />
      </div>
    </div>
    <!-- 列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh"
      :style="{ 'height': refreshHeight, background: '#fff' }">
      <van-list v-model:loading="loading" :finished="finished" @load="onLoad" :immediate-check="false">
        <template v-slot:finished>
          <div class="nothing_div" v-if="list.length == 0 && !refreshing">
            <van-image :src="nothingData"></van-image>
            <div class="nothing_font">暂无数据</div>
          </div>
        </template>
        <div v-for="(item, index) in list" :key="index" class="product_list_van_list_div"
          :style="{ 'background-color': item.checked ? '#E2F3FF' : '#fff' }">
          <van-swipe-cell>
            <van-checkbox v-show="multipleChoice" v-model="item.checked" @change="onCheckboxChange(item, $event)"
              :disabled="checkboxDis(item)" />
            <div class="commodity_list" ref="myElement" :style="{
              width: multipleChoice
                ? 'calc(100% - 4.4vw)'
                : '100%',
            }">
              <div class="list_top" @click="handleGetDetails(item.id)">
                <div class="list_top_img">
                  <van-image radius="5"
                    :src="item?.productImages ? item?.productImages + '?x-oss-process=image/resize,w_300' : icon_imgNull" />
                  <img src="" alt="">
                  <div class="list_top_img_tag" v-if="item?.hmMechanismsList[1]?.cooperationMode">
                  </div>
                </div>
                <div class="list_top_right">
                  <div class="list_top_right_title">
                    <div class="title">{{ item?.styleName }}</div>
                    <div class="status" :style="computedAtatusColor(auditStatusNameById(item.auditStatus))">{{
                      item.auditStatus == 13 && item.receiveStatus == 0 ? '待接收' : auditStatusNameById(item.auditStatus)
                    }}
                    </div>
                  </div>
                  <div class="list_top_right_introduce">{{ item?.sellingPoints }}</div>
                  <div class="list_top_right_library">
                    <span>{{ item.recruiterDept }}</span>
                    <span class="line">|</span>
                    <span>{{ item.recruiter }}</span>
                  </div>
                  <div class="list_top_right_money">
                    <div class="money_left">
                      <div v-if="item?.hmMechanismsList[0].cooperationMode === '分佣'">
                        ￥<span>{{ item?.hmMechanismsList[0].price }}</span>
                      </div>
                      <div v-if="item?.hmMechanismsList[0].cooperationMode === '供货'">
                        ￥<span>{{ item?.hmMechanismsList[0].costPrice }}</span>
                      </div>
                      <div v-if="item?.hmMechanismsList[0].cooperationMode === '分佣'" class="commission">
                        <span class="fonts">佣</span>
                        <span class="numbers">
                          {{ item?.hmMechanismsList[0].commission }}%
                        </span>
                      </div>

                      <div class="money_right" v-if="item?.hmMechanismsList[0].liveStreamingMechanism">
                        {{ item?.hmMechanismsList[0].liveStreamingMechanism }}
                      </div>
                    </div>
                    <!-- <div class="money_right" v-if="item?.hmMechanismsList[0].liveStreamingMechanism">
                      {{ item?.hmMechanismsList[0].liveStreamingMechanism }}
                    </div> -->
                  </div>

                  <!-- 无合同审批 -->
                  <div class="describe">
                    <div class="describe_left">
                      <template v-if="item.sellStatus == '1'">
                        <div class="describe_div"
                          :style="{ backgroundColor: item.sellStatus == '1' ? '#E7FDEE' : '#FDE7E7' }">
                          <div :style="{ color: item.sellStatus == '1' ? '#19D11B' : '#FC2540' }">合同
                          </div>
                          <van-image :src="item.sellStatus == '1' ? icon_duihaolvse : icon_wenhaohongse"></van-image>
                        </div>
                      </template>
                      <template v-else-if="item.sellStatus != '1' && item.bigBrandStatus == '1'">
                        <div class="describe_div mianqian">
                          <div>免签</div>
                        </div>
                      </template>
                      <template v-else-if="item.sellStatus != '1' && item.bigBrandStatus != '1'">
                        <div class="describe_div"
                          :style="{ backgroundColor: item.sellStatus == '1' ? '#E7FDEE' : '#FDE7E7' }">
                          <div :style="{ color: item.sellStatus == '1' ? '#19D11B' : '#FC2540' }">合同
                          </div>
                          <van-image :src="item.sellStatus == '1' ? icon_duihaolvse : icon_wenhaohongse"></van-image>
                        </div>
                      </template>

                      <div class="describe_department" v-if="item.coreName">
                        <van-image :src="icon_bumen"></van-image>
                        <div class="coreName">{{ item.coreName }}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

            </div>

            <!-- 待入库状态时删除左滑按钮 -->
            <template #right>
              <div class="button_div">
                <div class="button_list">
                  <div class="parmay" v-if="computAud(item.auditStatus, item.receiveStatus)?.buttonleft"
                    @click="audClick(computAud(item.auditStatus)?.buttonleft, item.id, item)" v-throttle:click :style="{
                      'color': computAud(item.auditStatus)?.buttonleftColor,
                      'background-color': computAud(item.auditStatus)?.buttonleftBackgroundColor
                    }">
                    <van-image :src="computAud(item.auditStatus)?.buttonleftAvator" />
                    <div>{{ computAud(item.auditStatus)?.buttonleft }}</div>
                  </div>
                  <div class="parmay" v-if="computAud(item.auditStatus, item.receiveStatus)?.buttonright" :style="{
                    'color': computAud(item.auditStatus)?.buttonrightColor,
                    'background-color': computAud(item.auditStatus)?.buttonrightAvatorBackgroundColor
                  }" @click="audClick(computAud(item.auditStatus)?.buttonright, item.id, item)" v-throttle:click>
                    <van-image :src="computAud(item.auditStatus)?.buttonrightAvator" />
                    <div>{{ computAud(item.auditStatus)?.buttonright }}</div>
                  </div>
                </div>
              </div>
            </template>
          </van-swipe-cell>
          <div class="line_b"></div>
        </div>


      </van-list>
    </van-pull-refresh>

    <!-- 多选操作 -->
    <div class="button" v-if="multipleChoice">
      <div class="cancel" @click="cancel">取消已选</div>
      <div class="outbound" @click="outbound" v-if="queryParams.auditStatus == 8" v-throttle:click>入库 ({{
        selectedItems.length
      }})
      </div>
      <div class="outbound" @click="receipt" v-if="queryParams.auditStatus == 2" v-throttle:click>确认收货 ({{
        selectedItems.length
      }})
      </div>
      <div class="outbound" @click="putaway" v-if="queryParams.auditStatus == 4" v-throttle:click>上架 ({{
        selectedItems.length
      }})
      </div>
      <div class="outbound" @click="approval" v-if="queryParams.auditStatus == 6" v-throttle:click>送审 ({{
        selectedItems.length
      }})
      </div>
    </div>

    <!-- 新增商品 -->
    <van-image :src="icon_tianjiashangpin" class="add_product" @click="addProduct"></van-image>
    <!-- 无合同审批 -->
    <van-calendar v-model:show="showCalendar" @confirm="onConfirm" />
    <van-overlay :show="noContractApprovalFlag" z-index="6001">
      <div class="wrapper" @click.stop>
        <div class="wrapper_div">
          <van-image :src="colseImg" @click="close"></van-image>
          <div class="title">审批附言</div>
          <van-form @submit="noContractSubmit">
            <div class="label">请选择补充合同日期</div>
            <van-field v-model="suppContractDate" class="dates" readonly name="calendar" label="" placeholder="日期选择"
              @click="showCalendar = true" />
            <div class="label">审批附言</div>
            <van-field maxlength="50" show-word-limit v-model="message" rows="6" label="" type="textarea"
              placeholder="请输入审批附言" :border="false" />

            <van-button class="buttons" round block type="primary" native-type="submit" v-throttle:click>
              提交确认
            </van-button>
          </van-form>
        </div>
      </div>
    </van-overlay>
    <!-- 资质送审 -->
    <van-overlay :show="qualificationsFlag" z-index="6001">
      <div class="wrapper_qualifications" @click.stop>
        <div class="wrapper_div">
          <van-image class="close" :src="colseImg" @click="qualificationsclose"></van-image>
          <div class="title">选择送审品类</div>
          <div class="describe">请为您的商品选择送审的品类</div>
          <div class="column">
            <div class="lable">可选品类</div>
            <div class="value" @click="categoryFlag = true">
              {{ categoryMessage || '请选择' }}
              <van-image :src="icon_heisexiasanjiao"></van-image>
            </div>
          </div>
          <van-popup v-model:show="categoryFlag" position="bottom">
            <van-picker title="可选品类" :columns="categoryColumns" @confirm="onConfirmCategory"
              @cancel="categoryFlag = false" />
          </van-popup>
          <div class="buttons">
            <div class="cancel" @click="qualificationsCancel">取消</div>
            <div class="save" @click="qualificationsSubmit">
              <template v-if="loading">
                <van-loading type="spinner" size="24px" color="#fff"> 执行中...</van-loading>
              </template>
              <template v-else>
                确定
              </template>
            </div>
          </div>
        </div>
      </div>
    </van-overlay>
    <!-- 二次确认退还供应商 -->
    <van-dialog v-model:show="dialogShow" :showConfirmButton="false">
      <div class="dialog_top">
        <van-image :src="icon_erciqueren"></van-image>
        <div class="title">确认退还</div>
        <div class="describe">
          确认将选中商品退还供应商？
        </div>
      </div>
      <div class="postscript">
        <div class="buttons">
          <div class="cancel" @click="dialogShow = false">取消</div>
          <div class="submit" @click="returnSubmit">确认</div>
        </div>
      </div>
    </van-dialog>

    <category :isShow="isShow" @leftClick="leftClick" @onSubmit="onSubmit" v-model:value="queryParams.categoryId" />
    <anchorSelection :isShow="isShowAnchor" @goback="goback" @onSubmit="anchorOnSubmit" :id="activeId">
    </anchorSelection>
    <van-action-sheet title="商品状态" v-model:show="statusShow" :actions="statusList" @select="onSelectCategory" />
    <van-action-sheet title="部门" v-model:show="investmentShow" :actions="investmentList" @select="onSelectInvestment" />

    <van-popup v-model:show="investmentShows" round position="bottom">
      <van-picker title="部门" :columns="investmentList" @confirm="investmentListonConfirm" @cancel="onCancel"
        :columns-field-names="customFieldName" />
    </van-popup>
  </div>
</template>
<script setup lang="ts">
import { auditStatusNameById } from "@/utils/auditStatusFilter";
import Qs from "qs";
import { listSupplierAddProduct, reAuditSecond, editTwo, editFour, editFive, outSupplier, queryOperationDeptList, editCore, editOff, editSeven, editSevens, editTen, noContractAdd } from "@/api/productList/index";
import { getEnvValue } from "@/utils/index";
import anchorSelection from '@/components/anchorSelection/index.vue'
import { againStock } from '@/api/productHome/index.ts'
import category from '@/components/category/index.vue'
import { getSystemList, getDeptAndUserTreeList } from '@/api/approval/index'
import { getInfo } from "@/api/supplierList/index";
import { ref, onMounted, onUnmounted, watch, computed, onActivated, reactive } from 'vue';
import { useRoute, useRouter } from "vue-router";
import { showDialog, showFailToast, showSuccessToast } from "vant";
import { userStore } from "@/store/user";
import { getDicts } from '@/api/productList/index'
import { storeToRefs } from "pinia";
import { getLastNonEmptyValue, getLastNonEmptyList } from '@/utils'
const nothingData = new URL("@/assets/porduct/icon_zanwushuju.png", import.meta.url).href
const heisexiasanjiao = new URL("@/assets/productHome/icon_heisexiasanjiao.png", import.meta.url).href;
const icon_duihaolvse = new URL("@/assets/productHome/icon_duihaolvse1.png", import.meta.url).href;
const icon_wenhaohongse = new URL("@/assets/newui/productList/icon_hongsecha@2x.png", import.meta.url).href;
const icon_bumen = new URL("@/assets/productHome/icon_bumen.png", import.meta.url).href;
const icon_tianjiashangpin = new URL("@/assets/productHome/icon_tianjiashangpin.png", import.meta.url).href;
const colseImg = new URL("@/assets/approval/close.png", import.meta.url).href;
const icon_heisexiasanjiao = new URL("@/assets/productHome/icon_heisexiasanjiao.png", import.meta.url).href;
const icon_erciqueren = new URL("@/assets/operation/icon_erciqueren.png", import.meta.url).href;
const icon_imgNull = new URL("@/assets/newui/imgNull.jpg", import.meta.url).href;
const store = userStore();
const { user } = storeToRefs(store);
const router = useRouter();
const route = useRoute();
// 搜索字段
const searchValue = ref("");
// 搜索弹窗
const showTop = ref(false)
// 搜索字段
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  styleName: "",
  auditStatus: "",
  supplierName: ""
});

// 宋丝语账号【recruitLeader】column设置
const customFieldName = ref({
  text: 'label',
  value: 'id',
  children: 'children',
})

/** 商品status */
const uniquekey = computed(() => {
  return route.query.id;
});

// 部门名称
const deptName = ref()

// 选中主播时商品id
const activeId = ref<string>()
// 主播选品
const isShowAnchor = ref(false)
// 商品类目检索
const catName = ref('商品类目')
// 商品类目弹窗
const isShow = ref<any>(false)
// 商品状态检索
const ststusName = ref('商品状态')
// 商品状态弹窗
const statusShow = ref(false)
// 商品状态
const statusList = ref<any[]>([])
// 招商部门检索
const investmentName = ref('部门')
// 招商部门弹窗
const investmentShow = ref(false)
// 宋丝语专属弹窗
const investmentShows = ref(false)
// 部门
const investmentList = ref<any[]>([])
// 招商部门展示权限
const userName = ref<any>([])
// 筛选多个弹窗
const showPop = ref(false)
// 筛选多个弹窗商品状态
const statusIndex = ref<any>()
// 筛选多个弹窗选品主播
const anchorList = ref<{ deptName: string; deptId: string }[]>([]);
// 筛选多个弹窗选品主播index
const anchorIndex = ref()
// 多选选项开关
const multipleChoice = ref(false);
// 存储选中的项
const selectedItems = ref<any[]>([]);
// 控制外部跳转进来切换商品状态失效问题
const flag = ref(false);
// 无合同补充合同日期
const suppContractDate = ref('');
// 无合同日期筛选显隐
const showCalendar = ref(false);
// 无合同审批附言
const message = ref('')
// 无合同审批当条数据内容
const avtiveItem = ref()
// 无合同审批显隐
const noContractApprovalFlag = ref(false)
// 资质审核显隐
const qualificationsFlag = ref(false)

// 资质审核可选品类显隐
const categoryFlag = ref(false)
// 资质审核可选品类column
const categoryColumns = ref([])
// 资质审核可选品类值
const categoryMessage = ref()
// 资质审核可选品类id
const categoryId = ref()
// 资质审核对应操作的商品id
const qualificationsProductId = ref()

// 退还弹窗
const dialogShow = ref(false)
// 退还商品id
const retrunId = ref()


// 列表刷新状态管理
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const list = ref<any[]>([]);
// 限制连续刷新数据重复问题
const refreFlag = ref(true)

const vantListScrollTop = ref<any>(0) // 滚动位置
const defaultPhoneHeight = ref(0) //屏幕默认高度
const nowPhoneHeight = ref(0) //屏幕现在的高度
const productsHeight = ref() // 总高度
const refreshHeight = ref() // 刷新组件高度
// 在组件挂载完成后添加事件监听器
onMounted(async () => {
  defaultPhoneHeight.value = window.innerHeight;
  // 添加事件监听器
  window.addEventListener('resize', handleResize);
  functionScroll('init')
  await getStatus()
  await getList()
})
// 处理窗口大小变化的函数
const handleResize = () => {
  nowPhoneHeight.value = window.innerHeight;
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  functionScroll('delete')
});
/** 缓存页面进度条 */
const functionScroll = (type: string) => {
  const dom: any = document.querySelector('.van-pull-refresh')
  if (type === 'init') {
    dom?.addEventListener('scroll', (e: any) => {
      vantListScrollTop.value = e.target.scrollTop
    })
  } else if (type === 'delete') {
    dom?.removeEventListener('scroll', () => { });
  } else if (type === 'black') {
    dom.scrollTop = vantListScrollTop.value
  }
}
onActivated(() => {
  functionScroll('black')
})
const emits = defineEmits(['doShow'])
watch(nowPhoneHeight, () => {
  if (defaultPhoneHeight.value != nowPhoneHeight.value) {
    // 当软键盘弹出,改变bottomIsSHow变量然后去控制bottom的显示与隐藏
    emits('doShow', false)
    productsHeight.value = '100vh'
    refreshHeight.value = 'calc(100vh - 50.4vw)'
  } else {
    // 相等代表软键盘收起后,与上同理
    emits('doShow', true)
    productsHeight.value = 'calc(100vh - 13.3vw)'
    refreshHeight.value = 'calc(100vh - 63.7vw)'
  }
})
/** 按商品名称搜索 */
const onSearch = () => {
  showTop.value = false
  queryParams.value.supplierName = '';
  queryParams.value.brandName = '';
  queryParams.value.styleName = searchValue.value;
  onRefresh();
};
/** 按供应商名称搜索 */
const onSearchs = () => {
  showTop.value = false
  queryParams.value.styleName = '';
  queryParams.value.brandName = '';
  queryParams.value.supplierName = searchValue.value;
  onRefresh();
};
/** 按品牌名字搜索 */
const onSearchBrand = () => {
  showTop.value = false
  queryParams.value.styleName = '';
  queryParams.value.supplierName = '';
  queryParams.value.brandName = searchValue.value;
  onRefresh();
}
/** 商品类目 */
const screenClicks = () => {
  isShow.value = true
}
/** 类目搜索查询 */
const onSubmit = (arr: any, tier: number) => {
  catName.value = arr[tier - 1].categoryName == '全部' ? '商品类目' : arr[tier - 1].categoryName
  isShow.value = false
  onRefresh()
}
/** 类目导航返回 */
const leftClick = () => {
  isShow.value = false
}
/** 获取商品状态 */
const getStatus = async () => {
  const res = await getDicts('hm_product_status')
  // 已下架 已退还 pc字典上不展示
  res.data.push(
    {
      dictLabel: '已下架',
      dictValue: '-1',
    },
  )
  res.data.push(
    {
      dictLabel: '已退还',
      dictValue: '-2',
    },
  )
  statusList.value = res.data.map((item: any) => {
    return {
      name: item.dictLabel,
      status: item.dictValue,
      color: '#323233'
    }
  })
  statusList.value.unshift({
    name: '全部', status: '', color: '#0094FF'
  })
}
/** 商品状态点击 */
const statusClick = () => {
  statusShow.value = true
}
/** 商品状态选择事件 */
const onSelectCategory = (selection) => {
  if (!refreFlag.value) {
    showFailToast('查询进行中请稍后，请勿重复点击')
  } else {
    statusShow.value = false;
    queryParams.value.auditStatus = selection.status
    statusList.value.forEach((item: any) => { item.color = '#323233' })
    selection.color = '#0094FF'
    ststusName.value = selection.name == '全部' ? '商品状态' : selection.name
    statusIndex.value = statusList.value.findIndex(item => item.status == selection.status)
    flag.value = true;
    multipleChoice.value = false
    onRefresh()
  }
}
/** 获取招商部门列表 */
const getsList = async () => {
  const res = await getDeptAndUserTreeList({})
  if (res.data && res.data.length) {
    if (user.value.indexOf('recruitLeader') != -1) {
      // 取招商部
      const department = res.data.filter(item => item.id == '1861962988832542721')[0].children
      department.unshift({
        label: '全部',
        id: null,
        children: []
      })
      department.forEach(element => {
        element.children.unshift({
          label: '全部',
          id: ''
        })
        // element.userList.forEach(item => {
        //   item.label = item.nickName
        //   item.id = item.userId
        // })
        // element.children = [...element.children, ...element.userList]
        // element.children.forEach(item => {
        //   if(item.userList){
        //     item.userList.forEach(items => {
        //       items.label = items.nickName
        //       items.id = items.userId
        //     })
        //     item.children = item.userList
        //   }else{
        //     item.children = []
        //   }
        // })
      });
      investmentList.value = department

    } else if (user.value.indexOf('recruitContractAudit') != -1) { //无合同
      res.data.unshift({
        label: '全部',
        id: null,
        children: []
      })
      res.data.forEach(element => {
        element.children.unshift({
          label: '全部',
          id: ''
        })
      });
      investmentList.value = res.data
    } else {
      res.data.unshift({
        label: '全部',
        id: null
      })
      res.data.forEach(item => {
        item.name = item.label
        item.status = item.id
      })
      investmentList.value = res.data
    }
  }
  const response = await getInfo()
  userName.value = user.value
  deptName.value = response.data.user.dept.deptName
}
getsList()
/** 招商部门点击 */
const investmentClick = () => {
  // 宋丝语
  if (user.value.indexOf('recruitLeader') != -1 || user.value.indexOf('recruitContractAudit') != -1) {
    investmentShows.value = true
  } else {
    investmentShow.value = true
  }
}
/** 招商部门选择事件 宋丝语*/
const investmentListonConfirm = ({ selectedValues, selectedOptions }) => {
  if (!refreFlag.value) {
    showFailToast('查询进行中请稍后，请勿重复点击')
  } else {
    investmentShows.value = false;
    queryParams.value.recruiterDeptId = getLastNonEmptyValue(selectedValues)

    // investmentList.value.forEach((item: any) => { item.color = '#323233' })
    // selection.color = '#0094FF'
    investmentName.value = getLastNonEmptyList(selectedOptions).label
    onRefresh()
  }
}
/** 取消产品部门选择  */
const onCancel = () => {
  investmentShows.value = false
}
/** 招商部门选择事件 */
const onSelectInvestment = (selection) => {
  if (!refreFlag.value) {
    showFailToast('查询进行中请稍后，请勿重复点击')
  } else {
    investmentShow.value = false;
    queryParams.value.recruiterDeptId = selection.id
    investmentList.value.forEach((item: any) => { item.color = '#323233' })
    selection.color = '#0094FF'
    investmentName.value = selection.name == '全部' ? '部门' : selection.name
    onRefresh()
  }
}
/** 多个筛选 商品状态点击 */
const statusClicks = (index: number) => {
  if (statusIndex.value == index) {
    statusIndex.value = undefined
  } else {
    statusIndex.value = index
  }
}
/** 获取主播 */
const getAnchor = async () => {
  const res = await queryOperationDeptList()
  anchorList.value = res.data
}
getAnchor()
/** 多个筛选 选品主播点击 */
const anchorClicks = (index: number) => {
  if (anchorIndex.value == index) {
    anchorIndex.value = undefined
  } else {
    anchorIndex.value = index
  }
}
/** 重置 */
const reset = () => {
  statusIndex.value = undefined
  anchorIndex.value = undefined
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    styleName: "",
    auditStatus: "",
    supplierName: ""
  }
  statusList.value.forEach((item: any) => { item.color = '#323233' })
  statusList.value[0].color = '#0094FF'
  ststusName.value = '商品状态'
}
/** 主播返回 */
const goback = () => {
  isShowAnchor.value = false
}
/** 选品主播提交 */
const anchorOnSubmit = async (coreId: string, coreName: string, sessionIndex: string, coreDeptId: string) => {
  await editCore({
    id: activeId.value,
    coreId,
    coreName,
    liveType: sessionIndex,
    coreDeptId
  });
  showSuccessToast({ type: "success", message: "主播选品成功" });
  onRefresh();
  closeArrayLight()
  isShowAnchor.value = false
}
/** 完成 */
const submit = () => {
  if (!refreFlag.value) {
    showFailToast('查询进行中请稍后，请勿重复点击')
  } else {
    // 商品状态
    if (statusIndex.value !== undefined && statusIndex.value !== null && statusIndex.value !== '') {
      queryParams.value.auditStatus = statusList.value[statusIndex.value].status

      statusList.value.forEach((item: any) => { item.color = '#323233' })
      statusList.value[statusIndex.value].color = '#0094FF'
      ststusName.value = statusList.value[statusIndex.value].name == '全部' ? '商品状态' : statusList.value[statusIndex.value].name
    } else {
      // queryParams.value.auditStatus = undefined
    }
    // 选品主播
    if (anchorIndex.value !== undefined && anchorIndex.value !== null && anchorIndex.value !== '') {
      queryParams.value.coreId = anchorList.value[anchorIndex.value].deptId
    } else {
      queryParams.value.coreId = undefined
    }


    flag.value = true;
    showPop.value = false
    onRefresh();
  }
}
/** 取消 */
const cancel = () => {
  list.value.forEach(item => {
    item.checked = false
  })
  selectedItems.value = [];
};
/** 入库 */
const outbound = async () => {
  if (selectedItems.value.length > 0) {
    const ids = selectedItems.value.map(item => item.id)
    await editTen(Qs.stringify({ ids: [ids] }, { arrayFormat: 'repeat' }));
    showSuccessToast({ type: "success", message: "商品入库成功" });
    multipleChoice.value = !multipleChoice.value
    onRefresh();
    closeArrayLight()
  } else {
    showFailToast('请选择入库商品');
  }
};
/** 批量确认收货 */
const receipt = async () => {
  if (selectedItems.value.length > 0) {
    const ids = selectedItems.value.map(item => item.id)
    await editFour(Qs.stringify({ ids: [ids] }, { arrayFormat: 'repeat' }));
    showSuccessToast({ type: "success", message: "商品确认收货成功" });
    multipleChoice.value = !multipleChoice.value
    onRefresh();
    closeArrayLight()
  } else {
    showFailToast('请选择收货商品');
  }
};
/** 批量上架 */
const putaway = async () => {
  if (selectedItems.value.length > 0) {
    const ids = selectedItems.value.map(item => item.id)
    await editFive(Qs.stringify({ ids: [ids] }, { arrayFormat: 'repeat' }));
    showSuccessToast({ type: "success", message: "商品上架成功" });
    multipleChoice.value = !multipleChoice.value
    onRefresh();
    closeArrayLight()
  } else {
    showFailToast('请选择上架商品');
  }
};
/** 批量送审 */
const approval = async () => {
  if (selectedItems.value.length > 0) {
    const ids = selectedItems.value.map(item => item.id)
    await editSeven(Qs.stringify({ ids: [ids] }, { arrayFormat: 'repeat' }));
    showSuccessToast({ type: "success", message: "商品送审成功" });
    multipleChoice.value = !multipleChoice.value
    onRefresh();
    closeArrayLight()
  } else {
    showFailToast('请选择送审商品');
  }
};
// 清除多选数组
const closeArrayLight = () => {
  selectedItems.value = [];
  list.value.forEach(item => {
    item.checked = false
  })
}
/** 查询商品列表 */
const getList = async () => {
  loading.value = true;
  refreFlag.value = false
  if (uniquekey.value && !flag.value) {
    queryParams.value.auditStatus = uniquekey.value;
    // 商品状态回显
    statusList.value.forEach((item: any) => { item.color = '#323233' })
    const index = statusList.value.findIndex(item => item.status == uniquekey.value)
    statusList.value[index].color = '#0094FF'
    ststusName.value = statusList.value[index].name == '全部' ? '商品状态' : statusList.value[index].name
    // 筛选多个弹窗商品状态回显
    statusIndex.value = index
  }
  const res = await listSupplierAddProduct(queryParams.value);
  res.rows.forEach(async (item) => {
    if (item.productImage) {
      item.productImages = getEnvValue("VITE_APP_PIC_URL") + item.productImage.split(',')[0];
    } else {
      item.productImages = "";
    }
  });
  setTimeout(() => {
    refreFlag.value = true
    // 空数据 停止加载
    if (res.rows.length == 0) {
      list.value = [];
      finished.value = true;
      return;
    }
    // 有数据 赋值列表 加载状态结束
    res.rows.forEach((item) => {
      finished.value = false;
      list.value.push(item);
    });
    loading.value = false;
    refreshing.value = false;
    // 如果list长度大于等于总数据条数，数据全部加载完成
    if (list.value.length >= res.total) {
      finished.value = true; //结束加载
    }
  }, 400);
};
/** 加载更多 */
const onLoad = async () => {
  await getList();
  queryParams.value.pageNum++;
};
// 下拉
const onRefresh = () => {
  if (refreFlag.value) {
    refreFlag.value = false
    finished.value = false; // 清空列表数据
    refreshing.value = false;
    loading.value = true; // 加载状态
    queryParams.value.pageNum = 1; // 分页数赋值为1
    list.value = []; // 清空数组
    onLoad(); // 重新加载数据
  } else {
    finished.value = false;
    refreshing.value = false;
  }
}
// 筛选
const handleListFlag = () => {
  multipleChoice.value = false
  showTop.value = false
  // 筛选
  showPop.value = !showPop.value
};
/** 多选回显权限 */
const rightText = () => {
  // if (['8', '2', '4', '6'].includes(queryParams.value.auditStatus)) {
  //     if (list.value.length > 0) {
  //         return '多选'
  //     }
  // } else {
  // }
  // 暂时关闭多选
  return ''
}
/** 点击展示多选 */
const onClickRight = () => {
  // 隐藏时删除留存状态
  if (multipleChoice.value) {
    selectedItems.value = [];
    list.value.forEach(item => {
      item.checked = false
    })
  }
  multipleChoice.value = !multipleChoice.value
}
/** 选中事件 */
const onCheckboxChange = (item, checked) => {
  if (!checked) {
    const index = selectedItems.value.findIndex(
      (selected) => selected.id === item.id
    );
    if (index !== -1) {
      selectedItems.value.splice(index, 1);
    }
  } else {
    selectedItems.value.push(item);
  }
};
/** 多选禁用 */
const checkboxDis = (item: any) => {
  if (item.auditStatus == 2) {
    return false
  }
  if (item.auditStatus == 4) {
    return false
  }
  if (item.auditStatus == 6) {
    return false
  }
  // 上传过合同
  if (item.sellStatus == 1) {
    return false
    // 无合同审批
  } else if (item.sellStatus == 0) {
    // 经理审核通过
    if (item.contractAuditingStatus == 3) {
      return false
      //  0 提交了无合同入库 1 已驳回  2主管审核通过  null 没有提交
    } else {
      return true
    }
  }
}
/** 设置不同状态不同样式 */
const computedAtatusColor = (name: any) => {
  if (name.includes('待') || name.includes('中') || name.includes('未')) {
    return { backgroundColor: '#EBF4FF', color: '#0094FF' }
  } else if (name.includes('驳回') || name == '已下架' || name == '已退还') {
    return { backgroundColor: '#FDE7E7', color: '#FC2540' }
  } else {
    return { backgroundColor: '#E7FDEE', color: '#19D11B' }
  }
}
/** 不同状态对应的按钮以及样式 */
const buttonList = reactive([
  {
    buttonleft: "已邮寄",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_yiyouji@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "",
    buttonrightAvator: '',
    buttonrightColor: "",
    buttonrightAvatorBackgroundColor: '',
    status: '0',
  },
  {
    buttonleft: "待收货",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_yidaoyang@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "",
    buttonrightAvator: '',
    buttonrightColor: "",
    buttonrightAvatorBackgroundColor: '',
    status: '1',
  },
  {
    buttonleft: "确认收货",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_querenshouhuo@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "",
    buttonrightAvator: '',
    buttonrightColor: "",
    buttonrightAvatorBackgroundColor: '',
    status: '2',
  },
  {
    buttonleft: "修改机制",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_xiugaijizhi@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "",
    buttonrightAvator: '',
    buttonrightColor: "",
    buttonrightAvatorBackgroundColor: '',
    status: '3',
  },
  {
    buttonleft: "上架",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_shangjia@2x.png", import.meta.url).href,
    buttonleftColor: '#19D11B',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "",
    buttonrightAvator: '',
    buttonrightColor: "",
    buttonrightAvatorBackgroundColor: '',
    status: '4',
  },
  {
    buttonleft: "主播选品",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_xuanpin@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '5',
  },
  {
    buttonleft: "发起初审",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_songshen@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '6',
  },
  {
    buttonleft: "",
    buttonleftAvator: '',
    buttonleftColor: '',
    buttonleftBackgroundColor: '',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '7',
  },
  {

    buttonleft: "发起初审",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_songshen@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '8',
  },
  {

    buttonleft: "发起初审",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_songshen@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '9',
  },
  {

    buttonleft: "发起初审",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_songshen@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '10',
  },
  {
    buttonleft: "",
    buttonleftAvator: new URL("@/assets/porduct/submitCensorship.png", import.meta.url).href,
    buttonleftColor: '#fff',
    buttonleftBackgroundColor: '#0094FF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '11',
  },
  {

    buttonleft: "价格复审",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_shenpi@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '12',
  },
  {

    buttonleft: "无合同审批",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_shenpi@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '13',
  },
  {
    buttonleft: "入库",
    buttonleftAvator: new URL("@/assets/newui/productList/iocn_ruku@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '14',
  },
  {
    buttonleft: "入库",
    buttonleftAvator: new URL("@/assets/newui/productList/iocn_ruku@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '15',
  },
  {
    buttonleft: "",
    buttonleftAvator: new URL("@/assets/porduct/submitCensorship.png", import.meta.url).href,
    buttonleftColor: '#fff',
    buttonleftBackgroundColor: '#0094FF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '16',
  },
  {
    buttonleft: "重新入库",
    buttonleftAvator: new URL("@/assets/newui/productList/iocn_ruku@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '17',
  },
  {

    buttonleft: "变价审核",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_shenpi@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "",
    buttonrightAvator: new URL("@/assets/porduct/removeShelves.png", import.meta.url).href,
    buttonrightColor: "#fff",
    buttonrightAvatorBackgroundColor: '#FC2540',
    status: '18',
  },
  {
    buttonleft: "",
    buttonleftAvator: new URL("@/assets/porduct/submitCensorship.png", import.meta.url).href,
    buttonleftColor: '#fff',
    buttonleftBackgroundColor: '#0094FF',

    buttonright: "",
    buttonrightAvator: new URL("@/assets/porduct/removeShelves.png", import.meta.url).href,
    buttonrightColor: "#fff",
    buttonrightAvatorBackgroundColor: '#FC2540',
    status: '19',
  },
  {

    buttonleft: "变价审核",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_shenpi@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "",
    buttonrightAvator: new URL("@/assets/porduct/removeShelves.png", import.meta.url).href,
    buttonrightColor: "#fff",
    buttonrightAvatorBackgroundColor: '#FC2540',
    status: '20',
  },
  {

    buttonleft: "变价审核",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_shenpi@2x.png", import.meta.url).href,
    buttonleftColor: '#0094FF',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "",
    buttonrightAvator: new URL("@/assets/porduct/removeShelves.png", import.meta.url).href,
    buttonrightColor: "#fff",
    buttonrightAvatorBackgroundColor: '#FC2540',
    status: '21',
  },
  {
    buttonleft: "",
    buttonleftAvator: new URL("@/assets/porduct/submitCensorship.png", import.meta.url).href,
    buttonleftColor: '#fff',
    buttonleftBackgroundColor: '#0094FF',

    buttonright: "下架",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '22',
  },
  {
    buttonleft: "上架",
    buttonleftAvator: new URL("@/assets/newui/productList/icon_shangjia@2x.png", import.meta.url).href,
    buttonleftColor: '#19D11B',
    buttonleftBackgroundColor: '#F6FAFF',

    buttonright: "退还",
    buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
    buttonrightColor: "#FC2540",
    buttonrightAvatorBackgroundColor: '#F6FAFF',
    status: '-1',
  },
  {
    buttonleft: "",
    buttonleftAvator: new URL("@/assets/porduct/listing.png", import.meta.url).href,
    buttonleftColor: '#fff',
    buttonleftBackgroundColor: '#19D11B',

    buttonright: "",
    buttonrightAvator: new URL("@/assets/porduct/removeShelves.png", import.meta.url).href,
    buttonrightColor: "#fff",
    buttonrightAvatorBackgroundColor: '#FC2540',
    status: '-2',
  },
]);
/** 设置不同状态左滑文字 */
const computAud: any = (auditStatus: string, receiveStatus?: any) => {
  if (receiveStatus == 0 && auditStatus == '13') {
    return {
      buttonleft: "",
      buttonleftAvator: new URL("@/assets/newui/productList/icon_shenpi@2x.png", import.meta.url).href,
      buttonleftColor: '#0094FF',
      buttonleftBackgroundColor: '#F6FAFF',

      buttonright: "下架",
      buttonrightAvator: new URL("@/assets/newui/productList/icon_tuihuan@2x.png", import.meta.url).href,
      buttonrightColor: "#FC2540",
      buttonrightAvatorBackgroundColor: '#F6FAFF',
      status: '13',
    }
  } else {
    const match = buttonList.find(
      (element) => element.status == auditStatus
    );
    return match; // 如果找到匹配项，返回其 buttonright，否则返回默认值
  }
};
/** 补充合同日期 */
const onConfirm = (date) => {
  suppContractDate.value = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  showCalendar.value = false;
};
/** 无合同审批关闭 */
const close = () => {
  noContractApprovalFlag.value = false
}
/** 无合同审批提交 */
const noContractSubmit = async () => {
  if (!suppContractDate.value) {
    showFailToast({ message: "请选择补充合同日期", teleport: '.wrapper_div' });
  } else if (!message.value) {
    showFailToast({ message: "请输入审批附言", teleport: '.wrapper_div' });
  } else {
    // 无合同审批
    await noContractAdd({ productsId: avtiveItem.value.id, supplementTime: suppContractDate.value, recruiterRemark: message.value, auditDeptId: '' })
    showSuccessToast({ type: 'success', message: '无合同审批提交成功', teleport: '.wrapper_div' });
    noContractApprovalFlag.value = false
    suppContractDate.value = ''
    message.value = ''
    onRefresh();
    closeArrayLight()
  }
}
/** 左滑对应的点击事件 */
const audClick = async (title: string, id: string, item: any) => {
  if (title == '已邮寄') {
    router.push(`/orderNumber/${id}`);
  } else if (title == '已到样') {
    await editTwo({ id: id });
    showSuccessToast({ type: "success", message: "商品到样确认成功" });
    onRefresh();
    // 清除待入库时留存的状态
    closeArrayLight()
  } else if (title == '确认收货') {
    await editFour(Qs.stringify({ ids: [id] }, { arrayFormat: 'repeat' }));
    showSuccessToast({ type: "success", message: "商品确认收货成功" });
    onRefresh();
    // 清除待入库时留存的状态
    closeArrayLight()
  } else if (title == '修改机制') {
    router.push({
      path: `/editProduct/${id}`,
      query: { type: "type" },
    });
  } else if (title == '上架') {
    await editFive(Qs.stringify({ ids: [id] }, { arrayFormat: 'repeat' }));
    showSuccessToast({ type: "success", message: "商品上架成功" });
    onRefresh();
    // 清除待入库时留存的状态
    closeArrayLight()
  } else if (title == '退还') {
    retrunId.value = id
    dialogShow.value = true
  } else if (title == '主播选品') {
    isShowAnchor.value = true
    activeId.value = id
  } else if (title == '下架') {
    await editOff(Qs.stringify({ ids: [id] }, { arrayFormat: 'repeat' }));
    showSuccessToast({ type: "success", message: "商品下架成功" });
    onRefresh();
    // 清除待入库时留存的状态
    closeArrayLight()
  } else if (title == '入库') {
    // 无合同驳回时
    if (item.auditStatus == 14) {
      if (item.sellStatus == '1') {
        // 入库
        await editTen(Qs.stringify({ ids: [item.id] }, { arrayFormat: 'repeat' }));
        showSuccessToast({ type: "success", message: "产品入库中" });
        onRefresh();
        // 清除待入库时留存的状态
        closeArrayLight()
      } else if (item.bigBrandStatus == "1" && item.sellStatus == "0") {
        // 入库
        await editTen(Qs.stringify({ ids: [item.id] }, { arrayFormat: 'repeat' }));
        showSuccessToast({ type: "success", message: "产品入库中" });
        onRefresh();
        // 清除待入库时留存的状态
        closeArrayLight()
      } else { // 无合同审批
        showDialog({
          title: '无法入库',
          message: '当前商品暂无供销合同，请关注供销合同上传或无合同审批进展...',
        })
      }
    } else {
      // 入库
      await editTen(Qs.stringify({ ids: [item.id] }, { arrayFormat: 'repeat' }));
      showSuccessToast({ type: "success", message: "产品入库中" });
      onRefresh();
      // 清除待入库时留存的状态
      closeArrayLight()
    }
  } else if (title == '重新入库') {
    // 重新入库
    await againStock({ id: item.id });
    showSuccessToast({ type: "success", message: "产品重新入库中" });
    onRefresh();
    // 清除待入库时留存的状态
    closeArrayLight()
  } else if (title == '发起初审') {
    if (deptName.value != '食品部' && deptName.value != '鞋帽部' && deptName.value != '百货部' && deptName.value != '酒茶部' && deptName.value != '箱包部' && deptName.value != '服装部') {
      qualificationsFlag.value = true
      qualificationsProductId.value = id
    } else {
      // 商品初审
      await editSevens({ ids: [id] })
      showSuccessToast({ type: "success", message: "商品送审成功" });
      onRefresh();
      // 清除待入库时留存的状态
      closeArrayLight()
    }
  } else if (title == '变价审核') {
    router.push({
      path: '/mechanismPriceChange',
      query: {
        id: item.id
      }
    });
  } else if (title == '价格复审') {
    // 商品二审
    await reAuditSecond({ id: id })
    showSuccessToast({ type: "success", message: "商品送审成功" });
    onRefresh();
    // 清除待入库时留存的状态
    closeArrayLight()
  } else if (title == '无合同审批') {
    avtiveItem.value = item
    noContractApprovalFlag.value = true
  }
}

/** 退还供应商 */
const returnSubmit = async () => {
  await outSupplier({ ids: [retrunId.value] })
  showSuccessToast({ type: "success", message: "商品退还成功" });
  dialogShow.value = false
  onRefresh();
  // 清除待入库时留存的状态
  closeArrayLight()
}
/** 资质送审关闭 */
const qualificationsclose = () => {
  qualificationsFlag.value = false
}

const categoryMap = {
  '鞋帽': '1',
  '酒茶': '2',
  '箱包': '3',
  '百货': '4',
  '服装': '5',
  '食品': '6'
}

/** 可选品类column */
const getcategoryColumns = async () => {
  const res = await getSystemList({ parentId: '1796913597400784898' })
  if (res.data.length) {
    // 去掉惠麦优选部门
    const response = res.data.filter(item => item.deptName !== '惠麦优选')
    response.forEach(item => {
      item.text = item.deptName
      Object.keys(categoryMap).forEach(key => {
        if (item.deptName.includes(key)) {
          item.value = categoryMap[key];
          return;
        }
      });
    })
    categoryColumns.value = response
  }
}
getcategoryColumns()


/** 可选品类筛选 */
const onConfirmCategory = ({ selectedOptions }) => {
  categoryMessage.value = selectedOptions[0]?.text;
  categoryId.value = selectedOptions[0]?.value;
  categoryFlag.value = false
}
/** 可选品类取消 */
const qualificationsCancel = async () => {
  categoryMessage.value = ''
  qualificationsFlag.value = false
}
/** 可选品类提交 */
const qualificationsSubmit = async () => {
  if (!categoryMessage.value) {
    showFailToast({ message: "请选择可选品类", teleport: '.wrapper_div' });
  } else {
    // 商品预审
    loading.value = true
    try {
      await editSevens({ ids: [qualificationsProductId.value], productType: categoryId.value })
      loading.value = false
      showSuccessToast({ type: "success", message: "商品送审成功" });
      qualificationsFlag.value = false
      categoryMessage.value = ''
      onRefresh();
      // 清除待入库时留存的状态
      closeArrayLight()
    } catch (error) {
      if (error == 'timeout') {
        showFailToast('商品送审失败');
      }
      loading.value = false
    }
  }
}
/** 新增商品跳转 */
const addProduct = () => {
  router.push({
    path: '/addProduct',
    query: { from: 'productList' }
  })
}
/** 获取详情 */
const handleGetDetails = (id: string) => {
  router.push({
    path: `/productDetail/${id}`,
  });
};
</script>
<script lang="ts">
export default { name: 'productList' }
</script>
<style lang="less" scoped>
@import url(@/views/productList/index_newui.less);
</style>